package com.ear.orange.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ear.orange.common.BaseContext;
import com.ear.orange.entity.ShoppingCart;
import com.ear.orange.mapper.ShoppingCardMapper;
import com.ear.orange.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author orange
 */
@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCardMapper, ShoppingCart> implements ShoppingCartService {

    @Autowired
    private ShoppingCardMapper shoppingCardMapper;

    @Override
    public ShoppingCart addProduct(ShoppingCart shoppingCart) {
        //获取当前 登录用户的 购物车信息
        ShoppingCart result = getUserShoppingCart(shoppingCart);

        if (result != null) {
            //购物车里面有，那就是数量加一
            Integer number = result.getNumber();
            result.setNumber(number + 1);
            shoppingCardMapper.updateProduct(result);
        } else {
            //购物车里面没有，那就是需要创建一个商品信息到购物车里面
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCardMapper.addProduct(shoppingCart);
            result = shoppingCart;
        }
        return result;
    }

    @Override
    public List<ShoppingCart> listProducts() {
        //获取当前 登录用户的id
        Long userId = BaseContext.getCurrentId();
        List<ShoppingCart> list = shoppingCardMapper.listProducts(userId);
        return list;
    }

    @Override
    public void cleanProducts() {
        Long userId = BaseContext.getCurrentId();
        shoppingCardMapper.cleanProducts(userId, null, null);
    }

    @Override
    public ShoppingCart decreaseProduct(ShoppingCart shoppingCart) {
        //获取当前 登录用户的 购物车信息
        ShoppingCart result = getUserShoppingCart(shoppingCart);

        //购物车里面有，那就是数量减1
        Integer number = result.getNumber();
        result.setNumber(number - 1);
        //判断如果result.getNumber = 0时候，直接清空
        if (result.getNumber() <= 0) {
            shoppingCardMapper.cleanProducts(result.getUserId(), result.getDishId(), result.getSetmealId());
        } else {
            shoppingCardMapper.updateProduct(result);
        }
        return result;
    }

    private ShoppingCart getUserShoppingCart(ShoppingCart shoppingCart) {
        //获取当前 登录用户的id
        Long userId = BaseContext.getCurrentId();

        shoppingCart.setUserId(userId);
        ShoppingCart result = shoppingCardMapper.selProduct(shoppingCart);

        return result;
    }
}
